class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_filter :initializeErrors
  before_filter :authorize
  before_filter :getGames

  protected
     def initializeErrors
          @errors = [] #shared with every function on authorized page load
     end
     
     def getQuote(s)
          url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22#{s}%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="
          resp = Net::HTTP.get_response(URI.parse(url))
          data = resp.body
          json = ActiveSupport::JSON.decode(data)
          quote = json["query"]["results"]["quote"]
          return nil if quote["PreviousClose"] == nil

          #must determine change status
          if quote["Change"] == "0.00" 
               change = "nochange"
          elsif /(\+|-)/.match(quote["Change"])[0] == "+"
               change = "gain"
          else
               change = "loss"
          end
          
          {
               :previousClose => (quote['PreviousClose'].to_f*100).to_i,
               :name => quote["Name"],
               :symbol => quote["symbol"],
               :price => (quote['LastTradePriceOnly'].to_f*100).to_i,
               :change => change
          }
     end
     
     def getWatchedStocks(userid)
          stocks = []
          User.find(userid).watched_stocks.each do |watch|
               quote = self.getQuote(watch.symbol)
               @errors << "No stock info for symbol: #{watch.symbol}" if quote == nil
               stock = {"symbol"=>watch.symbol, "price"=>quote[:price], "change"=>quote[:change]}
               stocks << stock
          end
          
          #Sort by symbol
          stocks.sort do |a,b|
               a["symbol"]<=>b["symbol"]
          end
          stocks
     end
     
     #this should return a hash of 3 items, pendinggames, activegames, and completedgames
     #each will be associated with a list.
     def getGames()
          current_user = @current_user
          pendingGames = []
          activeGames = []
          completedGames =[]
          for m in current_user.matches do
               entry = {name: m.title, 
               capital: (m.users_matches.where(user_id: current_user.id).first.capital), url: (game_url m)}
               if m.finished then
                    completedGames << entry
               elsif m.pending
                    pendingGames << entry
               else
                    activeGames << entry
               end              
          end
          
          @pendingGames = pendingGames
          @activeGames = activeGames
          @completedGames = completedGames
     end
  
     def changeQuickwatch
          add = params['commit'] == "Add"
          sym = params["symbol"]
          badstock = self.getQuote( sym ) == nil or sym == ""
          if add and not badstock
               if @quickWatch.select{ |q| q["symbol"] == sym }.length != 0
                    @errors << "That stock is already in your list!" 
               else
                    stock = WatchedStock.new("symbol"=>sym, "user_id"=>@current_user.id)
                    stock.save
                    redirect_to dash_url
               end
          elsif not badstock
               if @quickWatch.select{ |q| q["symbol"] == sym }.length == 0
                    @errors << "That stock is not in your list!" 
               else
                 stock = WatchedStock.find_by({:symbol=>sym, :user_id=>@current_user.id})
                 WatchedStock.destroy(stock.id)
                 redirect_to dash_url
               end
          else
               @errors << "That stock symbol is not valid"
          end
     end   
  
     def sanitize(s)
          ActionController::Base.helpers.sanitize s
     end

     def authorize
          @current_user = User.find_by(id: session[:user_id])
          unless @current_user
               redirect_to login_url 
               return
          end
          
          #any time a logged in user accesses a page they must authorize so we update
          #their active time here
          @current_user.active = Time.now 
          @current_user.save

     end
end
